package com.fast.develop.integration.orm.resolver;

import com.fast.develop.integration.orm.converter.DateConverter;
import com.fast.develop.integration.orm.converter.PersistenceConverter;
import com.fast.develop.integration.orm.id.MetaDomainModelsVisit;
import com.fast.develop.meta.dm.MetaDomainModel;
import com.fast.develop.meta.dm.MetaField;
import com.fast.develop.meta.dm.enums.BasicFieldType;
import com.fast.develop.meta.dm.field.FieldType;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 莫寅
 * @createTime 2022-06-20 11:41
 * @desc：
 */
public class FieldTypeResolver {


    private Map<FieldType, PersistenceConverter> persistenceConverters = new HashMap<>();


    private MetaDomainModelsVisit metaDomainModelsVisit;


    public FieldTypeResolver(MetaDomainModelsVisit metaDomainModelsVisit) {
        this.metaDomainModelsVisit = metaDomainModelsVisit;
        persistenceConverters.put(BasicFieldType.Date, new DateConverter());
    }

    private Object convert(Object value, MetaField metaField){
        PersistenceConverter persistenceConverter = persistenceConverters.get(metaField.getType().type());
        if(persistenceConverter != null){
            return persistenceConverter.conver(value, metaField);
        }
        return value;
    }

    private void resolveValue(Map map, MetaField metaField){
        String fieldName = metaField.getName();
        Object preConvertValue = map.get(fieldName);
        Object convertValue = convert(preConvertValue, metaField);
        map.put(fieldName, convertValue);
    }


    public void resolve(String meta, Map map){
        MetaDomainModel metaDomainModel = metaDomainModelsVisit.getMeta(meta);
        if(metaDomainModel != null){
            metaDomainModel.getFields().stream().forEach(metaField -> {
                resolveValue(map, metaField);
            });
        }

    }
}
